package cn.site.modules.sys.service;

import cn.site.core.security.Digests;
import cn.site.core.utils.Encodes;
import cn.site.modules.sys.dao.UserDao;
import cn.site.modules.sys.entity.User;
import cn.site.modules.sys.security.SystemAuthorizingRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by ZGJ on 2015/3/8.
 */
@Service
@Transactional(readOnly = true)
public class SystemService {

    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;

    @Autowired
    private UserDao userDao;


    /**
     * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
     * @param plainPassword
     * @return
     */
    public static String entryptPassword(String plainPassword) {
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
        return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
    }

    /**
     * 验证密码
     * @param plainPassword 明文密码
     * @param password 密文密码
     * @return 验证成功返回true
     */
    public static boolean validatePassword(String plainPassword, String password) {
        byte[] salt = Encodes.decodeHex(password.substring(0,16));
        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
        return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword));
    }


    //-- User Service --//

    public User getUser(String id){

        return userDao.findOne(id);
    }

    public User getUserByLoginName(String loginName) {

        return userDao.findByLoginName(loginName);
    }

    public List findUser(){

        /*DetachedCriteria dc = userDao.createDetachedCriteria();
        if (StringUtils.isNotEmpty(user.getLoginName())){
            dc.add(Restrictions.like("loginName", "%"+user.getLoginName()+"%"));
        }
        if (StringUtils.isNotEmpty(user.getName())){
            dc.add(Restrictions.like("name", "%"+user.getName()+"%"));
        }*/
        return userDao.findAll();
    }

    @Transactional(readOnly = false)
    public void saveUser(User user){
        //清缓存
        //userDao.clear();
        userDao.save(user);
        //为什么需要清空所有关联认证???因为有可能是更新???
        //systemRealm.clearAllCachedAuthorizationInfo();
    }

}
